var mysql = require('mysql');
var config = require('../config')
var pool  = mysql.createPool(config.mysql);

type MysqlResult = { results: any, fields: any}

export function insertAnimation(data: any){
  return insert('insert into animation SET ?', data)
}

export function findAnimationByGuid(guid: string){
  return query('select 1 as c from animation where guid = ?', [ guid ])
}

export function queryAnimationPagination(where: any, page = 1, limit = 10){
  if(Object.keys(where).length > 0){
    return query('select * from animation where ? order by pubDate desc limit ?,? ', [where, (page - 1) * limit, limit])
  }
  return query('select * from animation order by pubDate desc limit ?,? ', [(page - 1) * limit, limit])
}

export function release(callback?: any){
  pool.end(callback)
}

function query(query: string, where?: any): Promise<MysqlResult>{
  return new Promise((resolve, reject) => {
    if(where){
      pool.query(query, where,function (error: any, results: any, fields: any) {
        if (error) reject(error)
        resolve({ results, fields })
      });
    } else {
      pool.query(query, function (error: any, results: any, fields: any) {
        if (error) reject(error)
        resolve({ results, fields })
      });
    }
  })
 
}

function insert(query: string, data: any): Promise<MysqlResult>{
  return new Promise((resolve, reject) => {
    pool.query(query, data,function (error: any, results: any, fields: any) {
      if (error) reject(error)
      resolve({ results, fields })
    });
  })
}
 
